import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/expert/expert_top_entity.dart';
import 'package:ball_lion/entity/home/news_class_entity.dart';
import 'package:ball_lion/server/api/expert_api.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/expert/top/top_list_view.dart';

class TopListLogic extends GetxController {
  TopListLogic(this.type, this.sportsId);
  final TopType type;
  final int sportsId;
  List<NewsClassEntity>? condition;
  int conditionIndex = 0;
  List<ExpertTopEntity>? list;
  List<ExpertTopEntity>? originList;
  bool onlySale = false;
  final EasyRefreshController refreshController = EasyRefreshController();

  @override
  void onReady() {
    super.onReady();
    getCondition();
  }

  getCondition() async {
    if (type == TopType.mingzhong) {
      final result = await ExpertApi.getMingzhongCondition();
      if (result != null) {
        condition = result;
        var index =
            condition?.indexWhere((element) => element.name == "近7天") ?? -1;
        if (index != -1) conditionIndex = index;
        update();
        getData();
      }
    } else if (type == TopType.huibao) {
      final result = await ExpertApi.getHuibaoCondition();
      if (result != null) {
        condition = result;
        update();
        getData();
      }
    } else if (type == TopType.renqi) {
      final result = await ExpertApi.getRenqiCondition();
      if (result != null) {
        condition = result;
        update();
        getData();
      }
    } else {
      condition = [
        NewsClassEntity(id: 1, name: '当前连红'),
        NewsClassEntity(id: 2, name: '历史连红')
      ];
      update();
      getData();
    }
  }

  getData() async {
    List<ExpertTopEntity>? data;
    if (type == TopType.mingzhong) {
      data =
          await ExpertApi.getHitTop(condition![conditionIndex].id!, sportsId);
    } else if (type == TopType.huibao) {
      data = await ExpertApi.getProfitTop(
          condition![conditionIndex].id!, sportsId);
    } else if (type == TopType.renqi) {
      data =
          await ExpertApi.getRenqiTop(condition![conditionIndex].id!, sportsId);
    } else {
      data =
          await ExpertApi.getRedTop(condition![conditionIndex].id!, sportsId);
    }
    if (data != null) {
      originList = data;
      filterData();
      update();
    }
  }

  filterData() {
    if (!onlySale) {
      list = originList;
    } else {
      list = originList!.filter((item) => item.isSale == 1);
    }
  }

  onTapCondition(int index) {
    if (conditionIndex == index) {
      return;
    }
    Utils.onEvent("expert_rank_red_switch", params: {"tab": index});
    conditionIndex = index;
    update();
    getData();
  }

  onTapFilter() async {
    onlySale = !onlySale;
    filterData();
    update();
  }

  onRefresh() {
    getData();
  }
}
